package xyxy.ymh;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;
import java.util.Map;

public class SpringApplication {
    public static void run(Class<?> clazz) {
        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
        annotationConfigWebApplicationContext.register(clazz);
        annotationConfigWebApplicationContext.refresh();
        WebServer webServer = getWebServer(annotationConfigWebApplicationContext);
        webServer.start(annotationConfigWebApplicationContext);
    }

    private static WebServer getWebServer(AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext) {
        Map<String, WebServer> beansOfType = annotationConfigWebApplicationContext.getBeansOfType(WebServer.class);
        if (beansOfType.size()==0){
            throw  new NullPointerException();
        }
        if (beansOfType.size()>1) {
            throw new IllegalArgumentException();
        }
        return beansOfType.values().stream().findFirst().get();
    }
}
